package com.cjkj.auth.service;

import com.cjkj.auth.form.AppLoginBody;
import com.cjkj.common.core.domain.R;
import com.cjkj.common.core.exception.ServiceException;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.system.api.RemoteAppService;
import com.cjkj.system.api.domain.dto.APIWechatSessionDto;
import com.cjkj.system.api.domain.request.APIAppAccountReq;
import com.cjkj.system.api.model.AppletLoginUser;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 小程序登录服务类
 */
@Component
public class AppLoginService {

    @Resource
    private RemoteAppService remoteAppService;

    /**
     * 登录
     * @param loginBody
     * @return
     */
    public AppletLoginUser login(AppLoginBody loginBody){
        /*
         * 1.获取用户openId;
         * 2.根据用户openId获取用户信息；
         **/
        AppletLoginUser loginUser = new AppletLoginUser();
        APIAppAccountReq appAccountReq = new APIAppAccountReq();
        R<APIWechatSessionDto> sessionResult = remoteAppService.getOpenId(loginBody.getJsCode(), loginBody.getDataType());
        if(StringUtils.isNull(sessionResult) || StringUtils.isNull(sessionResult.getData())){
            throw new ServiceException("获取用户个人信息失败");
        }
        if (R.FAIL == sessionResult.getCode())
        {
            throw new ServiceException(sessionResult.getMsg());
        }
        if(StringUtils.isNotNull(sessionResult.getData().getErrcode())){
            throw new ServiceException("注册失败"+sessionResult.getData().getErrmsg());
        }
        R<AppletLoginUser> loginUserResult  = remoteAppService.getLoginUser(sessionResult.getData().getOpenid());
        if(StringUtils.isNull(loginUserResult) || R.FAIL == loginUserResult.getCode()){
            throw new ServiceException("注册失败：" +loginUserResult.getMsg());
        }
        if(loginUserResult.getData() == null){
            appAccountReq.setNickName(loginBody.getNickName());
            appAccountReq.setAvatarUrl(loginBody.getAvatarUrl());
            appAccountReq.setOpenid(sessionResult.getData().getOpenid());
            R<?> accountResult = remoteAppService.addAccount(appAccountReq);
            if(StringUtils.isNull(accountResult) || R.FAIL == accountResult.getCode()){
                throw new ServiceException("注册失败");
            }
            loginUser.setOpenid(sessionResult.getData().getOpenid());
            loginUser.setNickName(loginBody.getNickName());
            loginUser.setAvatarUrl(loginBody.getAvatarUrl());
        } else {
            loginUser.setOpenid(loginUserResult.getData().getOpenid());
            loginUser.setAccountId(loginUserResult.getData().getAccountId());
            loginUser.setNickName(loginBody.getNickName());
            loginUser.setAvatarUrl(loginBody.getAvatarUrl());
            loginUser.setDoctor(loginUserResult.getData().getDoctor());
        }
        return loginUser;
    }

}